/****************************************
 * 2018 - 2021 版权所有 CopyRight(c) 快程乐码信息科技有限公司所有, 未经授权，不得复制、转发
 */

package com.kclm.security.demo.service.impl;

import com.kclm.security.demo.entity.Group;
import com.kclm.security.demo.entity.Role;
import com.kclm.security.demo.entity.User;
import com.kclm.security.demo.mapper.GroupMapper;
import com.kclm.security.demo.mapper.UserMapper;
import com.kclm.security.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/******************
 * @Author yejf
 * @Version v1.0
 * @Create 2020-07-20 15:42
 * @Description 去数据库查询相关登录信息
 */
@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService, UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GroupMapper groupMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("通过UserDetailsService接口的loadUserByUsername方法来确定登录用户是否存在");
        //调用持久层来获取用户
        final User user = this.userMapper.findByUserName(username);
        //
        if(null == user) {
            log.warn("用户：[{}] 不存在。", username);
            throw new UsernameNotFoundException("用户名不存在");
        }
        //创建List集合，用来保存用户的角色信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        //获取当前用户的角色集合
        final List<Group> groups = user.getGroups();
        for(Group group : groups) {
            log.debug("加载组：[{}]所拥有的角色",group.getGroupName());
            final List<Role> roles = this.groupMapper.selectRolesByGroupId(group.getId()).get(0).getRoles();
            //把角色添加到 authorities集合中
            for(Role role : roles) {
                //
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
        }
        //
        log.debug("已加载完此用户下的所有用户组下的所有角色");
        //
        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getUserPwd(),authorities);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(User user) {
        //
        log.debug("-- 持久化用户对象");
        return this.userMapper.save(user);
    }
}
